package com.postpeakliving.store.client;

import java.util.Date;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.gwtext.client.core.Ext;
import com.gwtext.client.core.ExtElement;

public class AddToCart implements EntryPoint {
	private static final Date removeExpire = new Date((new Date()).getTime() + 0 );    			
	private static String title = "<span onclick='stopAddItem()'>Adding kit to shopping cart (click this message to stop).</span>";
	private static String logMessage = "";
	private static int callBackCounter = 0, errorCallBackCounter=0,maxItem=0;
	private ShopCart shopCart = new ShopCart();
	private static String domain = ".postpeakliving.com";
	private static String path   = "/";
	private static final String cookieName = "shopCart";
	
	private static boolean stopFlag = false;
	
	private static String preUrl="http://store.postpeakliving.com/";
	
	private Element maskElementTip;
	
	public void onModuleLoad() {
		defineBridgeMethod();
		final String cookieValue = Cookies.getCookie(cookieName);
		if(cookieValue != null && ! cookieValue.isEmpty()){
			showTipWindow();
			addToCart(cookieValue);
		}else{
			//do nothing
		}
	}
	
	private void showTipWindow(){
		ExtElement maskElement = Ext.getBody().mask(title,true);
		String maskId  = maskElement.getDOM().getId();
		maskElementTip = Ext.get(maskId).getDOM().getNextSiblingElement().getFirstChildElement();
	}
	
	private void addToCart(String jsonArrayUrlList){
		if(jsonArrayUrlList != null){
			JSONValue jsonValue       = JSONParser.parse(jsonArrayUrlList);
			shopCart   = ShopCart.jsonToJava(jsonValue);
			maxItem                   = shopCart.getItemCount();
			if(maxItem > 0) {
				callAmazonUrl();
			}
		}
	}
	
	
	private void callAmazonUrl(){
        if(stopFlag==true)return;
		String url = preUrl + shopCart.pop();
		RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,url);
	    try {
	      requestBuilder.sendRequest(null, new RequestCallback() {
	        public void onError(Request request, Throwable exception) {
				errorCallBackCounter += 1;
				logMessage = "<span onclick='stopAddItem()'>Adding product "+callBackCounter+" of "+maxItem+" to cart"+errorCallBackCounter+" failed. (click this message to stop).</span>";
				maskElementTip.setInnerHTML(logMessage);
	        }
	        public void onResponseReceived(Request request, Response response){
				callBackCounter += 1;
				logMessage       = "<span onclick='stopAddItem()'>Adding product "+callBackCounter+" of "+maxItem+" to cart (click this message to stop).</span>";
				maskElementTip.setInnerHTML(logMessage);
				if(callBackCounter == maxItem){
					stopAddItem();
				}else{
					//recursive call to emulate the synchronize request
					callAmazonUrl();
				}
	        }
	      }
	      );
	    } catch (RequestException ex) {
	       GWT.log(ex.getMessage(), ex);
	    }
	}
	
	//must be static, else defineBridgeMethod() cannot be compiled
	private static void stopAddItem(){
		stopFlag = true;
		Cookies.setCookie(cookieName,null, removeExpire,domain,path,false);
		Ext.getBody().unmask();
		//Safari only suport relative path redirect,don't use "preUrl+'cart.htm'"
		Window.open("cart.htm", "_self", "");
	}
	
    private static native void defineBridgeMethod() /*-{
   	$wnd.stopAddItem = function() {
       return @com.postpeakliving.store.client.AddToCart::stopAddItem()();    	
  	}
 	}-*/;	
	
}